package test;



import test.Ldap;
import java.util.HashMap;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.naming.NamingException;

/**
 *
 * @author Denis Jouvin
 */
@SuppressWarnings("unchecked")
public class User {

    private static Ldap conf = new Ldap();
    // Préparation de la "requete" LDAP
    private final static String FILTER_PATTERN = "(&(objectClass=inetOrgPerson)(uid=%))";
    private final static String SUBTREE = "ou=people";
    // Noms d'attributs LDAP
    private final static String NOM = "sn";
    private final static String PRENOM = "givenName";
    private final static String NOM_COMPLET = "cn";
    private final static String MAIL = "mail";
    // Attributs du bean
    private String id = "";
    private String nom = "";
    private String prenom = "";
    private String nomComplet = "";
    private String mail = "";
    // pour le caching (eviter de faire la requete à chaque fois)
    private boolean searched = false;

    /**
     * Fonction de recherche d'un élément dans l'annuaire (pas très optimisée et lance une exception si
     */
    private void search() {
        if (searched) {
            return;
        }
        if ((id == null) || id.equals("")) {
            throw new IllegalStateException("UID must be initialized before searching user in LDAP.");
        }
        String filter = FILTER_PATTERN.replaceAll("%", id);
        HashMap<String, String> attr;
        try {
            attr = conf.search(SUBTREE, filter);

            if(attr != null) {
                nom = attr.get(NOM);
                prenom = attr.get(PRENOM);
                nomComplet = attr.get(NOM_COMPLET);
                mail = attr.get(MAIL);
            }
            searched = true;
        } catch (NamingException ex) {
            Logger.getLogger(User.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

    public String getId() {
        return id;
    }

    public void setId(String id) {
        this.id = id;
    }

    public String getNom() {
        search();
        return nom;
    }

    public String getPrenom() {
        search();
        return prenom;
    }

    public String getNomComplet() {
        search();
        return nomComplet;
    }

    public String getMail() {
        search();
        return mail;
    }

    public void affiche() {
        System.out.println("toto");
    }
}